﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KL.Store.Web.Models;
using KL.Store.Data;
using KL.Store.Core;
using KL.Store.Core.Domain;
using System.Web.Caching;

namespace KL.Store.Web.Controllers
{
    public class CategoriesController : KL.Store.Core.Web.BaseController
    {
        #region Index

        public ActionResult Index(int? id, string goNewUrl = "")
        {
            ViewBag.Controller = "category_crtl";
            if (id.HasValue)
            {
                CategoryMeta cm = dbCategory.GetMeta((int)id);
                Category cd = dbCategory.Get((int)id);
                IList<Category> icd = dbCategory.GetList((int)id);


                if (cm != null && cd != null)
                {
                    if (!string.IsNullOrEmpty(goNewUrl) && cd.LinkUrl.Contains(goNewUrl))
                    {
                        return RedirectPermanent(cd.LinkUrl);
                    }
                    if (icd.Where(o => o.RelatedCategoryCount > 0 || o.RelatedItemCount > 0).Count() <= 0)
                    {
                        return Redirect(cd.LinkUrl.Replace("kategori/", "urunler/"));
                    }

                    ViewBag.Title = string.IsNullOrEmpty(cm.WebTitle) ? cm.CategoryName : cm.WebTitle;
                    ViewBag.Keywords = string.IsNullOrEmpty(cm.Keywords) ? Parameters.WebSiteTitle + " " + cm.CategoryName : cm.Keywords;
                    ViewBag.Description = string.IsNullOrEmpty(cm.Description) ? Parameters.WebSiteTitle + " " + cm.CategoryName : cm.Description;
                    var websiteUrl = dbRefs.GetRef1(1913) == "E" ? Parameters.WebSiteUrl.Replace("http://", "https://") : Parameters.WebSiteUrl;
                    ViewBag.CanonicalUrl = websiteUrl + "/kategori" + cm.Canonical + "-" + cm.CategoryId + ".html";
                    eStoreUser.RedirectUrl = cd.LinkUrl;
                }
                else
                {
                    return Redirect("/Content/404");
                }
            }
            else
            {
                return Redirect("/Content/404");
            }

            return View();
        }

        #endregion

        #region Get

        [Child]
        public ActionResult Get(int? id)
        {
            CategoryModel categoryModel = new CategoryModel();
            if (id.HasValue)
            {
                Category cd = dbCategory.Get((int)id);
                categoryModel.RelatedCategories = dbCategory.GetList((int)id);
                if (categoryModel.RelatedCategories.Count() < 1) { Response.Redirect(cd.LinkUrl.Replace("/kategori", "/urunler")); }
                if (categoryModel.RelatedCategories == null) { categoryModel.RelatedCategories = new List<Category>(); }
                categoryModel.RelatedItemCount = categoryModel.RelatedCategories.Count();

                Category category = dbCategory.Get((int)id);
                if (category != null)
                {
                    categoryModel.CategoryId = category.CategoryId;
                    categoryModel.CategoryName = category.CategoryName;
                    categoryModel.CategoryType = category.CategoryType;
                    categoryModel.ImageUrl = category.ImageUrl;
                    categoryModel.BannerActive = category.BannerActive;
                    categoryModel.ParentBannerActive = category.ParentBannerActive;
                    categoryModel.ParentCategoryId = category.ParentCategoryId;
                    categoryModel.IsManager = eStoreUser.IsManager;
                    categoryModel.IsSeoManager = eStoreUser.IsSeoManager;
                }
                categoryModel.BreadCrumb = dbCategory.GetBreadCrumb((int)id, Parameters.MainCategoryId, Parameters.HomePageCategoryId, eStoreUser.CultureInfo);
            }

            if (string.IsNullOrEmpty(categoryModel.BreadCrumb)) { categoryModel.BreadCrumb = "Kategori Bulunamadı"; }

            return PartialView(categoryModel);
        }

        #endregion

        #region GetSubCategories

        public ActionResult GetSubCategories(int? id)
        {
            CategoryModel categoryModel = new CategoryModel();
            if (id.HasValue)
            {
                Category cd = dbCategory.Get((int)id);
                categoryModel.RelatedCategories = dbCategory.GetList((int)id);
                if (categoryModel.RelatedCategories.Count() < 1) { Response.Redirect(cd.LinkUrl.Replace("/kategori", "/urunler")); }
                if (categoryModel.RelatedCategories == null) { categoryModel.RelatedCategories = new List<Category>(); }
                categoryModel.RelatedItemCount = categoryModel.RelatedCategories.Count();

                Category category = dbCategory.Get((int)id);
                if (category != null)
                {
                    categoryModel.CategoryId = category.CategoryId;
                    categoryModel.CategoryName = category.CategoryName;
                    categoryModel.ImageUrl = category.ImageUrl;
                    categoryModel.BannerActive = category.BannerActive;
                    categoryModel.ParentBannerActive = category.ParentBannerActive;
                    categoryModel.ParentCategoryId = category.ParentCategoryId;
                }
                categoryModel.BreadCrumb = dbCategory.GetBreadCrumb((int)id, Parameters.MainCategoryId, Parameters.HomePageCategoryId, eStoreUser.CultureInfo);
            }

            if (string.IsNullOrEmpty(categoryModel.BreadCrumb)) { categoryModel.BreadCrumb = "Kategori Bulunamadı"; }

            return PartialView(categoryModel);
        }


        #endregion

        #region GetProductsInCat

        [Child]
        public ActionResult GetProductsInCat(int? id, int? brand, int? sort, int? order, int? itemCount, decimal? minPrice, decimal? maxPrice, string multipleBrands)
        {
            var cacheKey = "GetProductsInCat" + id + brand + sort + order + itemCount + minPrice + maxPrice + multipleBrands;
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                ViewBag.Page = 1;
                return PartialView(HttpRuntime.Cache[cacheKey] as KL.Store.Web.Models.ProductsModel);
            }
            ProductsModel productsModel = new ProductsModel();
            productsModel.Sort = 1;
            productsModel.Order = 1;
            productsModel.BasketLocked = eStoreUser.BasketLocked;

            if (id.HasValue)
            {
                CategoryMeta cm = dbCategory.GetMeta((int)id);
                if (cm != null)
                {
                    productsModel.ColumnCount = cm.ColumnCount;
                    productsModel.ListImageType = cm.ListImageType;
                }
                else
                {
                    productsModel.ColumnCount = 4;
                    productsModel.ListImageType = "w";
                }

                if (!brand.HasValue) brand = 0;

                if (!sort.HasValue) sort = 1;
                if (!order.HasValue) order = 1;
                productsModel.Sort = (int)sort;
                productsModel.Order = (int)order;
                productsModel.Brand = (int)brand;
                ViewBag.Page = 1;

                var posListe = dbPos.GetList().Where(o => o.PosVoucher == "S").FirstOrDefault();
                if (posListe != null)
                {
                    posListe.PosInstallment = dbPos.GetInstallmentList(posListe.PosId, 1, 9999, 0, 0);
                    var VCR = posListe.PosInstallment.Where(o => o.InstallmentNumber == Parameters.SenetTaksit1).FirstOrDefault().CommissionRate;
                    var VCCR = posListe.PosInstallment.Where(o => o.InstallmentNumber == Parameters.SenetTaksit1).FirstOrDefault().CampaignCommissionRate;
                    productsModel.VoucherRate = posListe.PosInstallment != null && Parameters.SenetTaksit1 > 0 ? VCR : (1 + (Parameters.SenetEkUcret / 100));
                    productsModel.CampaignVoucherRate = posListe.PosInstallment != null && Parameters.SenetTaksit1 > 0 && VCCR > 0 ? VCCR : productsModel.VoucherRate;
                }
                if (!sort.HasValue)
                {
                    productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).ToArray<Product>();
                }
                else
                {
                    if (productsModel.Sort == 1)
                    {
                        if (productsModel.Order > 1)
                        {
                            productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).OrderByDescending(o => o.ProductName).ToArray<Product>();
                        }
                        else
                        {
                            productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).OrderBy(o => o.ProductName).ToArray<Product>();
                        }
                    }
                    else if (productsModel.Sort == 2)
                    {
                        if (productsModel.Order > 1)
                        {
                            productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).OrderByDescending(o => o.Price).ToArray<Product>();
                        }
                        else
                        {
                            productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).OrderBy(o => o.Price).ToArray<Product>();
                        }
                    }
                    else if (productsModel.Sort == 3)
                    {
                        if (productsModel.Order > 1)
                        {
                            productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).OrderByDescending(o => o.ProductId).ToArray<Product>();
                        }
                        else
                        {
                            productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).OrderBy(o => o.ProductId).ToArray<Product>();
                        }
                    }
                    else if (productsModel.Sort == 4)
                    {
                        if (productsModel.Order > 1)
                        {
                            productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).OrderByDescending(o => o.CreatedDate).OrderByDescending(o => o.BillOut).ToArray<Product>();
                        }
                        else
                        {
                            productsModel.RelatedProducts = dbProduct.GetListCat((int)id, (int)itemCount, eStoreUser.AccountId).OrderByDescending(o => o.CreatedDate).OrderBy(o => o.BillOut).ToArray<Product>();
                        }
                    }
                }
                if (productsModel.RelatedProducts.Count > 0)
                {
                    productsModel.MinPriceTotal = Convert.ToDecimal(productsModel.RelatedProducts.Min(o => o.Price));
                    productsModel.MaxPriceTotal = Convert.ToDecimal(productsModel.RelatedProducts.Max(o => o.Price));

                }

                Category category = dbCategory.Get((int)id);
                if (category != null)
                {
                    Mapper.MapDomainToViewModel(category, productsModel);
                }

            }

            if (string.IsNullOrEmpty(productsModel.BreadCrumb)) { productsModel.BreadCrumb = "Kategori Bulunamadı"; }
            HttpRuntime.Cache.Add(cacheKey, productsModel, null, DateTime.UtcNow.AddDays(1), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
            return PartialView(productsModel);
        }

        #endregion
    }
}
